package cn.stronglink.assetmanage.utils.dao;

import android.app.SearchableInfo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.dao.PatrolDetailDao;
import cn.stronglink.assetmanage.dao.RoomDao;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;

/**
 * 巡检数据库交互
 */
public abstract class PatrolDataUtil {

    /**
     * 保存巡检单到数据库
     */
    public static boolean savePatrolData(String resultJson) {
        Gson gson = new Gson();
        //id为单号 patrol_id是主键
        List<Patrol> patrolList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().queryBuilder().distinct()
                .orderAsc(PatrolDao.Properties.Id).list();

        Map<String, Patrol> patrolMap = new HashMap<>();    //巡检到的商品
        for (int i = 0; i < patrolList.size(); i++) {
            Patrol detail = patrolList.get(i);
            patrolMap.put(patrolList.get(i).getId_(), detail);
        }

        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
        Result<List<Patrol>> repairResult = null;
        repairResult = gson.fromJson(resultJson, new TypeToken<Result<List<Patrol>>>() {
        }.getType());
        if (repairResult != null && repairResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (repairResult.getData() != null) {
                //遍历下载的的patrol和数据库中的patrol， 如果数据库中有就将数据库中的patrol给下载的patrol列表
                List<Patrol> inventoryList = repairResult.getData();

                // 巡检单列表
                if (inventoryList != null && inventoryList.size() > 0) {
                    for (Patrol patrol : inventoryList) {
                        String id_ = patrol.getId_();
                        if (!patrolMap.containsKey(id_)) {
                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().insert(patrol);
                            // 获取详情
                            List<SearchAsset> searchAssetList = getSearchAssetByRoomId(patrol.getRoomId_());
                            savePatrolDetailData(patrol, searchAssetList,false);
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 获取巡检单
     */
    public static List<Patrol> getPatrol() {
        List<Patrol> patrolList = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().queryBuilder().distinct()
                .orderDesc(PatrolDao.Properties.Id_)
                .orderAsc(PatrolDao.Properties.BeginTime).list();
        if (patrolList != null || patrolList.size() != 0) {
            return patrolList;
        }

        return null;
    }

    /**
     * 保存巡检单到本地
     */
    public static boolean savePatrol(Patrol patrol) {
        try {
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().update(patrol);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据巡检单id获取巡检单
     */
    public static Patrol getPatrolById(String patrolId) {
        List<Patrol> patrolList = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().queryBuilder().distinct()
                .where(PatrolDao.Properties.Id_.eq(patrolId)).list();
        Patrol patrol = new Patrol();
        if (patrolList != null || patrolList.size() != 0) {
            patrol = patrolList.get(0);
        }

        if (patrol != null) {
            return patrol;
        }
        return null;
    }

    /**
     * 获取地点列表
     */
    public static List<Room> getAreaList() {
        List<Room> roomList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getRoomDao().loadAll();

        if (roomList != null || roomList.size() != 0) {
            return roomList;
        }
        return null;
    }

    /**
     * 获取资产列表
     *
     * @param patrolLocationName
     */
    public static List<SearchAsset> getSearchAsset(String patrolLocationName) {
        List<SearchAsset> searchAssetList = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao().queryBuilder()
                .where(SearchAssetDao.Properties.RoomName.eq(patrolLocationName)).distinct()
                .list();

        if (searchAssetList != null || searchAssetList.size() != 0) {
            return searchAssetList;
        }
        return null;
    }

    public static List<PatrolDetail> getPatrolDetailByOrderNo(String patrolId) {
        List<PatrolDetail> patrolDetailList = new ArrayList<>();
        patrolDetailList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().
                queryBuilder().distinct().where(PatrolDetailDao.Properties.OrderNo.eq(patrolId)).list();
        return patrolDetailList;
    }

    public static String getRoomNameByid(String roomId) {
        Room room = new Room();
        List<Room> roomList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRoomDao().queryBuilder()
                .distinct().where(RoomDao.Properties.Id_.eq(roomId)).list();
        if (roomList != null && roomList.size() > 0) {
            room = roomList.get(0);
        }
        return room.getName();
    }

    public static List<SearchAsset> getSearchAssetByRoomId(String roomId) {
        String roomName = getRoomNameByid(roomId);
        List<SearchAsset> assetList = getSearchAssetByBoomName(roomName);
        return assetList;
    }

    public static List<SearchAsset> getSearchAssetByBoomName(String roomName) {
        List<SearchAsset> assetList = new ArrayList<>();
        if ("全部地点".equals(roomName)) {
            assetList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT)
                    .getSearchAssetDao().queryBuilder().distinct().list();
        } else {
            assetList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                    getSearchAssetDao().queryBuilder().distinct().where(SearchAssetDao.Properties.RoomName
                    .eq(roomName)).list();
        }
        return assetList;
    }

    public static void savePatrolDetailData(Patrol patrol, List<SearchAsset> searchAssetList,boolean isInit) {
        if (searchAssetList != null && searchAssetList.size() > 0) {
            for (SearchAsset searchAsset : searchAssetList) {
                PatrolDetail patrolDetail = new PatrolDetail();
                patrolDetail.setOrderNo(patrol.getId_());
                saveSearchDataToPatrolDetail(patrolDetail, searchAsset,isInit);
            }
        }
    }

    public static void saveSearchDataToPatrolDetail(PatrolDetail patrolDetail, SearchAsset searchAsset,boolean isInit) {
        if (searchAsset.getStatus() == 1 || searchAsset.getStatus() == 2 ||
                searchAsset.getStatus() == 6 || !"".equals(searchAsset.getRackId_())) {
            patrolDetail.setOrderNo(patrolDetail.getOrderNo());
            patrolDetail.setAssetName(searchAsset.getAssetName());
            patrolDetail.setAssetNo(searchAsset.getAssetNo());
            patrolDetail.setBrandId(searchAsset.getBrandId());
            patrolDetail.setBrandId_(searchAsset.getBrandId_());
            patrolDetail.setBrandName(searchAsset.getBrandName());
            patrolDetail.setBuyTime(searchAsset.getBuyTime());
            patrolDetail.setDatacenterId(searchAsset.getDatacenterId());
            patrolDetail.setDatacenterId_(searchAsset.getDatacenterId_());
            patrolDetail.setEndUser(searchAsset.getEndUser());
            patrolDetail.setId(searchAsset.getId());
            patrolDetail.setAssetId(searchAsset.getId());
            patrolDetail.setId_(searchAsset.getId_());
            patrolDetail.setManageBranchId(searchAsset.getManageBranchId());
            patrolDetail.setManageBranchId_(searchAsset.getManageBranchId_());
            patrolDetail.setModelId(searchAsset.getModelId());
            patrolDetail.setModelId_(searchAsset.getModelId_());
            patrolDetail.setModelName(searchAsset.getModelName());
            patrolDetail.setPrice(searchAsset.getPrice());
            patrolDetail.setRackId(searchAsset.getRackId());
            patrolDetail.setRackId_(searchAsset.getRackId_());
            patrolDetail.setRackName(searchAsset.getRackName());
            patrolDetail.setRfidNo(searchAsset.getRfidNo());
            patrolDetail.setRoomId(searchAsset.getRoomId());
            patrolDetail.setRoomId_(searchAsset.getRoomId_());
            patrolDetail.setRoomName(searchAsset.getRoomName());
            patrolDetail.setSerialNo(searchAsset.getSerialNo());
            //未巡检
            if (isInit) {
                patrolDetail.setStatus(0);
            } else {
                patrolDetail.setStatus(patrolDetail.getStatus());
            }
            patrolDetail.setTypeId(searchAsset.getTypeId());
            patrolDetail.setTypeId_(searchAsset.getTypeId_());
            patrolDetail.setTypeName(searchAsset.getTypeName());
            patrolDetail.setUseBranchId(searchAsset.getManageBranchId());
            patrolDetail.setUseBranchId_(searchAsset.getManageBranchId_());
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                    getPatrolDetailDao().insertOrReplace(patrolDetail);
        }
    }

    public static SearchAsset getSearchAssetById_(String id_) {
        List<SearchAsset> searchAssetList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao()
                .queryBuilder().where(SearchAssetDao.Properties.Id_.eq(id_)).distinct().list();
        if (searchAssetList != null && searchAssetList.size() > 0) {
            return searchAssetList.get(0);
        }
        return null;
    }

    public static PatrolDetail getPatrolDetailDataById_(String id_) {
        List<PatrolDetail> patrolDetailList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT)
                .getPatrolDetailDao().queryBuilder().where(PatrolDetailDao.Properties.Id_.eq(id_)).distinct()
                .list();
        if (patrolDetailList != null && patrolDetailList.size() > 0) {
            return patrolDetailList.get(0);
        }
        return null;
    }

    public static void savePatrolDetail(PatrolDetail patrolDetail) {
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().insertOrReplace(patrolDetail);
    }

    public static void deletePatrol(Patrol patroll) {
        if (patroll != null) {
            List<PatrolDetail> patrolDetailList = getPatrolDetailByOrderNo(patroll.getId_());
            if (patrolDetailList != null) {
                for (PatrolDetail patrolDetail : patrolDetailList) {
                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().delete(patrolDetail);
                }
            }
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().delete(patroll);
        }
    }
}
